package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.common.enums.CustomizeEnum;
import com.example.demo.common.enums.QuestionEnum;
import com.example.demo.common.handler.CustomException;
import com.example.demo.entity.Comment;
import com.example.demo.entity.Question;
import com.example.demo.entity.User;
import com.example.demo.entity.dto.QuestionDTO;
import com.example.demo.mapper.QuestionMapper;
import com.example.demo.service.ifs.IQuestionService;
import com.example.demo.service.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ak
 * @since 2020-04-02
 */
@Service
@Slf4j
@CacheConfig(cacheNames = "questionList")
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {
    @Autowired
    QuestionMapper questionMapper;
    @Autowired
    CommentServiceImpl commentService;
    /**
     * 将发布的问题存入数据库
     */
    public void saveQuestion(Question question) {
        String formatTime = CommonUtils.getFormatTime();
        User user=(User)SecurityUtils.getSubject().getPrincipal();

        question.setQCreate(formatTime);
        //TODO 判断用户登录
        if (user!=null){
            question.setQAuthor(user.getUUsername());
            question.setUser(user);
        }
        //标签去重
        question.setQTags(checkTags(question.getQTags()));
        super.save(question);
        Integer questionId = question.getQId();
        log.info("已将问题id为{}的问题存入数据库", questionId);
    }

    /**
     * 根据id获取问题
     */
    public Question getQuestion(Integer questionId) {
        log.info("根据id获取问题，查询数据库");
        questionMapper.updateQuestionViewCount(questionId);
        return super.getById(questionId);
    }

    @Cacheable(keyGenerator = "bestKey")
    public Page<Question> getQuestionList(Integer pageIndex,Integer pageSize){
        log.info("获取问题列表，查询数据库");
        Page<Question> questionPage = new Page<>(pageIndex,pageSize);
        return super.page(questionPage, new QueryWrapper<Question>().select("*"));
    }

    @Cacheable(key = "#questionId")
    public QuestionDTO getQuestionMsgById(Integer questionId){
        Question question = getQuestion(questionId);
        List<Comment> commentList = commentService.getCommentList(questionId);
        User user = (User)SecurityUtils.getSubject().getPrincipal();
        QuestionDTO questionDTO = new QuestionDTO();
        questionDTO.setCommentList(commentList);
        questionDTO.setQuestion(question);
        questionDTO.setUser(user);
        questionDTO.setQuestionId(questionId);
        return questionDTO;
    }

    /**
     * 标签去重去重
     */
    private String checkTags(String tags) {
        String[] split = tags.split(",");
        HashSet<String> tagsSet = new HashSet<>(Arrays.asList(split));
        StringBuilder tagsBuilder = new StringBuilder();
        for (String s : tagsSet) {
            tagsBuilder.append(s).append(",");
        }
        return tagsBuilder.toString();
    }

    @Transactional(rollbackFor = Exception.class)
    public String test() throws CustomException {
        try {
            int i=1/0;
        }catch (Exception e){
            log.error("事务回滚了。。。");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "error";
        }
        System.out.println(111);
        return "true";
    }
}
